// 导入必要的模块和配置文件
import store from "@/store";
import { Message } from "element-ui";
import base64 from "base-64";
import Server from "/public/js/socket.io.js";
import configUrl from "/public/config/configUrl.json";

class Communication {
  constructor() {
    this.socketDamage = {
      client: null,
    };
    this.token = sessionStorage.getItem("usertoken") || "";
  }

  // 连接方法
  connect(userId, groupId) {
    const geturl = base64.decode(configUrl.signalling_host);
    const userIdValue = userId?.toString() || "";
    const groupIdValue = groupId?.toString() || "";
    const url = `${geturl}?userId=${userIdValue}&groupId=${groupIdValue}&token=${this.token}`;

    this.socketDamage.client = Server.connect(url, {
      timeout: 300000,
      reconnection: true,
      reconnectionDelayMax: 30000,
      reconnectionDelay: 1000,
    });

    // 信令连接报错提示
    this.socketDamage.client.on("connect_error", (data) => {
      console.log(JSON.stringify(data) + "io-connect_error");
      if (data) {
        Message.error("信令连接失败,请参照手册允许信令访问!");
      }
    });

    const u = navigator.userAgent;
    if (u.indexOf("Trident") > -1) {
      // IE
      Message.error("请使用极速模式!");
    }
  }

  // 监听事件方法
  on(eventName, callback) {
    this.socketDamage.client.on(eventName, (data) => callback(data));
  }

  // 发送事件方法
  emit(eventName, data, callback) {
    this.socketDamage.client.emit(eventName, data, (d) => callback(d));
  }

  // 断开连接方法
  disconnect() {
    this.socketDamage.client.disconnect();
  }

  // 警告音播放方法
  warningTonePlay(name) {
    const lv = document.getElementById("warningTone");
    lv.src = `/media/${name}.mp3`;
    lv.play();
  }

  // 警告音关闭方法
  warningToneClose() {
    const lv = document.getElementById("warningTone");
    lv.pause();
  }

  // 更新正在处理案件数 - 心跳方法
  updateHandleNum() {
    const taskid = store.getters.videoList;
    console.log("更新正在处理案件数", taskid);
    const param = {
      userId: this.user.userId,
      groupId: this.user.group,
      lineNum: taskid.length,
      taskArray: taskid,
      token: this.token,
    };

    this.emit("damage-online-heartbeat", param);
    console.log("updateHandleNum-------->", param);
  }

  // 初始化 socket 相关监听等操作
  socketInit(back, userId, groupId) {
    this.connect(userId, groupId);

    // 视频定损协议相关的各种事件监听
    this.on(`auditor-${userId}`, (res) => {
      console.log("back my message:" + JSON.stringify(res));
      const msg = { mode: "auditor", info: res };
      back(msg);
    });
    this.on(`chat-${userId}`, (res) => {
      console.log("back my message:" + JSON.stringify(res));
      const msg = { mode: "chat", info: res };
      back(msg);
    });
    this.on("online", (res) => {
      console.log("back my online:" + JSON.stringify(res));
      if (res.userId !== "") {
        const msg = { mode: "online", info: res };
        back(msg);
      }
    });
    this.on("cancel", (res) => {
      console.log("back my cancel:" + JSON.stringify(res));
      const msg = { mode: "cancel", info: res };
      back(msg);
    });
    this.on(`textchat-${userId}`, (res) => {
      console.log("back my textchat:" + JSON.stringify(res));
      const msg = { mode: "textchat", info: res };
      back(msg);
    });
    this.on("notice", (res) => {
      console.log("back my notice:" + JSON.stringify(res));
      const msg = { mode: "notice", info: res };
      back(msg);
    });
    this.on("reconnect", (res) => {
      // console.log("back my reconnect:" + JSON.stringify(res));
      const token = localStorage.getItem("token");
      this.emit("damage-online", {
        userId: userId,
        status: true,
        token: token,
      });
    });
    this.on("damager-task-notify", (res) => {
      console.log("damager-task-notify", res);
    });
    this.on("upload", (res) => {
      console.log("upload", res);
      console.log("back my message:" + JSON.stringify(res));
      store.dispatch("repairFactory/uploadNotice", res);
    });

    // 申请上下班相关监听
    this.on("apply", (res) => {
      console.log("apply", res);
      console.log("back my message:" + JSON.stringify(res));
      store.dispatch("repairFactory/applyMessage", res);
    });
  }

  // 关闭 socket 连接方法
  socketClose() {
    this.disconnect();
  }
}

// 创建并导出 Communication 类的实例
const communication = new Communication();
export default communication;
